import React, { useEffect, useState } from 'react';
import { Modal, Form, Button } from 'antd';
import { FormInstance } from 'antd/lib/form';
import { DeviceListItem } from '../data';
import ParentOrgListComponent from '../../System/components/ParentOrgListComponent';

interface CreateFormProps {
  modalVisible: boolean;
  loading: boolean;
  onSubmit: (values: DeviceListItem) => void;
  onCancel: () => void;
  values: DeviceListItem;
}

// const { Option } = Select;

const layout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 16 },
};

const formRef = React.createRef<FormInstance>();
let oldValue = "";
const DeviceOrgEditDialog: React.FC<CreateFormProps> = (props) => {
  const { modalVisible, loading, onSubmit, onCancel, values } = props;
  const [form] = Form.useForm();

  const handleFinish = (values: { [key: string]: any }) => {
    if (onSubmit) {
      onSubmit(values as DeviceListItem);
    }
  };

  const handleUpdate = () => {
    if (!form) return;
    form.submit();
  };

  useEffect(() => {
    if (modalVisible) {
      if (values && values.id) {
        form.setFieldsValue(values);
        oldValue = values.name;
      }
    }
  }, [modalVisible]);

  const renderContent = () => {
    return (
      <>
        <Form.Item name="id" style={{ display: 'none' }}></Form.Item>
        <Form.Item name="orgId" label="所属机构" rules={[{ required: true }]}>
          <ParentOrgListComponent
            defaultvalue={values ? values.orgId : -1}
            type="orgId"
            selectChange={(value) => {
              form.setFieldsValue({ "orgId": value });
            }}
          >
          </ParentOrgListComponent>
        </Form.Item>
      </>
    );
  };

  return (
    <Modal
      destroyOnClose
      width={400}
      title="修改机构"
      visible={modalVisible}
      onCancel={onCancel}
      footer={[
        <Button key="cancel" onClick={onCancel}>取消</Button>,
        <Button type="primary" loading={loading} onClick={handleUpdate}>确定</Button>
      ]}
    >
      <Form {...layout} ref={formRef} form={form} onFinish={handleFinish}>
        {renderContent()}
      </Form>
    </Modal>
  );
};

export default DeviceOrgEditDialog;
